<?php

require_once 'Zend/Mail.php';
require_once APPLICATION_PATH . '/configs/configuration.php';

class UserTestsController extends Zend_Controller_Action {

    protected $_authNamespace;

    public function init() {
        /* Initialize action controller here */
        $this->_authNamespace = new Zend_Session_Namespace('Zend_Auth');
        $this->session = new Zend_Session_Namespace('test');
    }

    public function indexAction() {
        /*
         * List available levels
         */

        $levelMapper = new Application_Model_LevelMapper();
        $this->view->levels = $levelMapper->fetchAll();
    }

    public function listTestsAction() {
        /*
         * List tests by level received by a get parameter
         */

        $level_id = $this->_getParam("level_id");
        $test = new Application_Model_TestMapper();
        $this->view->tests = $test->fetchByLevel($level_id);

        $this->_helper->layout()->setLayout('ajax');

    }

    public function doTestAction() {

        $test_id = $this->_getParam("test_id");
        $questionnaire_id = null;
        if ($this->_hasParam('questionnaire_id')) {
            $questionnaire_id = $this->_getParam("questionnaire_id");
        } //else {
        // the test starts, delete session data
        /*
        * la inicializacion se hace en el index ahora
        * para mantener la sesión
        */
          /*  if (isset($this->session->ok_responses)) {
                unset($this->session->ok_responses);
            }

            if (isset($this->session->fail_responses)) {
                unset($this->session->fail_responses);
            }

            if (isset($this->session->tries)) {
                unset($this->session->tries);
            }
        */

        //}

        $data = array("id" => $test_id);
        $test = new Application_Model_Test($data);
        $testMapper = new Application_Model_TestMapper();
        $this->view->tests = $testMapper->find($test_id, $test);


        $questionnaireMapper = new Application_Model_QuestionnaireMapper();

        $questionMapper = new Application_Model_QuestionMapper();
        $questionnaire = new Application_Model_Questionnaire();
        $result = $questionnaireMapper->fetchByTest($test_id);
        $this->view->questionnaires = $result;
        if ($questionnaire_id != null) {
            $data_q = array("id" => $questionnaire_id);
            $questionnaire = new Application_Model_Questionnaire($data_q);
            $questionnaireMapper->find($questionnaire_id, $questionnaire);

            $questions = $questionMapper->fetchByQuestionnaire($questionnaire->getId());
        } else {
            if (count($result) > 0) {
                $questionnaire = $result[0];
                $this->view->questionnaires = $result;

                $questions = $questionMapper->fetchByQuestionnaire($questionnaire->getId());
            } else {
                $questions = null;
                $this->view->message = "This test has no questionnaires!";
            }
        }

        $this->view->test = $test;
        $this->view->questionnaire = $questionnaire;
        $this->view->questions = $questions;

    }

    public function continueTestAction() {

        $test_id = $this->_getParam("test_id");
        $questionnaire_id = $this->_getParam("questionnaire_id");

        if ($test_id == null || $questionnaire_id == null) {
            $this->_helper->redirector("index");
        }

        $testMapper = new Application_Model_TestMapper();
        $questionnaireMapper = new Application_Model_QuestionnaireMapper();
        $questionMapper = new Application_Model_QuestionMapper();

        $data = array("id" => $test_id);
        $test = new Application_Model_Test($data);
        $testMapper->find($test_id, $test);

        $data = array("id" => $questionnaire_id);
        $questionnaire = new Application_Model_Questionnaire($data);
        $questionnaireMapper->find($questionnaire_id, $questionnaire);



        $fail_responses = array();
        $ok_responses = array();
        if ($this->getRequest()->isPost()) {
            $request = $this->getRequest();

            $questions = $questionMapper->fetchByQuestionnaire($questionnaire_id);
            $oks = 0;
            $fails = 0;

            foreach($questions as $q) {
                $response = $request->getParam("response_".$q->getId());
                $response = str_replace('\\', '', $response);
                $correct = $q->getResult();
                $ok = false;
                if (count($correct) > 0) {
                    foreach($correct as $res) {
                        if ($response == $res) {
                            $ok = true;
                            $oks++;
                            $ok_responses[] = array('response_'.$q->getId(), $correct);
                            break;
                        }
                    }

                }
                if (!$ok) {
                    $fails++;
                    $fail_responses[] = array('response_'.$q->getId(), $response);
                }

            }
            // update session data

            if (!isset($this->session->tries)) {
                $this->session->tries = array();
            }
            if (!isset($this->session->tries["$questionnaire_id"])) {
                $this->session->tries["$questionnaire_id"] = 0;
            }
            $this->session->tries["$questionnaire_id"]++;

            if (!isset($this->session->ok_responses)) {
                $this->session->ok_responses = array();
            }
            $this->session->ok_responses["$questionnaire_id"] = $ok_responses;

            if (!isset($this->session->fail_responses)) {
                $this->session->fail_responses = array();
            }
            $this->session->fail_responses["$questionnaire_id"] = $fail_responses;

            if ($questionnaire->getFailsNumber() >= $fails) {
            // if results are ok redirect to the next questionnaire
                $questionnaires = $questionnaireMapper->fetchByTest($test_id);
                for ($i=0; $i < count($questionnaires); $i++) {
                    if ($questionnaires[$i]->getId() == $questionnaire_id) {
                        break;
                    }
                }

                if (count($questionnaires) > $i+1) {
                    $next_questionnaire = $questionnaires[$i+1];
                    $result_url = '/user-tests/do-test/?test_id='.$test_id.'&questionnaire_id='.$next_questionnaire->getId();
                } else {
                    // redirect user to next level
                    // choose the next test
                    $level = new Application_Model_LevelMapper();
                    $data = array("id" => (int) $test->getLevelId());
                    $actual_level = new Application_Model_Level($data);
                    $level->find($test->getLevelId(), $actual_level);

                    $actual_level_id = $actual_level->getId();
                    $actual_level_level = $actual_level->getLevel();

                    $next_level_level = $actual_level_level+1;


                    $next_level = new Application_Model_Level();
                    $next_level = $level->fetchByLevel($next_level_level);

                    if ($next_level != null) {
                        $testMapper = new Application_Model_TestMapper();
                        $tests = $testMapper->fetchByLevel($next_level->getId());

                        if (count($tests) > 0) {
                            //$this->view->next_test_id = $tests[0]->getId();
                            $result_url = '/user-tests/do-test/?test_id='.$tests[0]->getId();
                        } else {
                            //return $this->_helper->redirector->gotoUrl('/user-tests/final-results/');
                            $result_url = '/user-tests/result-test/?test_id='.$test_id;
                        }
                    } else {
                        //redirect to finish page
                        //return $this->_helper->redirector->gotoUrl('/user-tests/final-results/');
                        $result_url = '/user-tests/result-test/?test_id='.$test_id;
                    }
                    
                }
                $result = 'ok';

            } else {
            // if results are not ok, redirect to the same questionnaire
                if ($this->session->tries["$questionnaire_id"] >= 2) {
                    // final result test!
                    $result_url = '/user-tests/result-test/?test_id='.$test_id;
                } else {
                    $result_url = '/user-tests/do-test/?test_id='.$test_id.'&questionnaire_id='.$questionnaire_id;
                }
                $result = 'fail';
            }
        }

        $redirect = '0';
        if ($this->session->tries["$questionnaire_id"] >= 2) {
            $redirect = '1';
        }
        $myResponse = array($result, $result_url, $fail_responses, $ok_responses, $redirect);

        $this->_helper->json($myResponse);

    }

    public function resultTestAction() {
        try {
            $test_id = $this->_getParam("test_id");

            if ($test_id == null || !isset($this->session->tries)) {
                $this->_helper->redirector->gotoUrl("/");
            }

            $testMapper = new Application_Model_TestMapper();


            $data = array("id" => $test_id);
            $test = new Application_Model_Test($data);
            $testMapper->find($test_id, $test);


            $questionnaire = new Application_Model_Questionnaire();
            $questionnaireMapper = new Application_Model_QuestionnaireMapper();
            $questionnaires = $questionnaireMapper->fetchByTest($test_id);

            $results = array();
            $all_ok = $all_fail = 0;
            foreach ($this->session->tries as $questionnaire_id => $tries) {
                $aux_q = new Application_Model_Questionnaire();
                $questionnaireMapper = new Application_Model_QuestionnaireMapper();
                $questionnaireMapper->find($questionnaire_id, $aux_q);
                $all_ok = $all_ok + count($this->session->ok_responses[$questionnaire_id]);
                $all_fail = $all_fail + count($this->session->fail_responses[$questionnaire_id]);

                $results[$aux_q->getName()] = array("questionnaire_id" => $questionnaire_id, "tries" => $tries, "n_fails" => count($this->session->fail_responses[$questionnaire_id]));

            }

            // choose the next test
            $level = new Application_Model_LevelMapper();
            $data = array("id" => (int) $test->getLevelId());
            $actual_level = new Application_Model_Level($data);
            $level->find($test->getLevelId(), $actual_level);

            $actual_level_id = $actual_level->getId();
            $actual_level_level = $actual_level->getLevel();

            $next_level_level = $actual_level_level+1;


            $next_level = new Application_Model_Level();
            $next_level = $level->fetchByLevel($next_level_level);

            if ($next_level != null) {
                $testMapper = new Application_Model_TestMapper();
                $tests = $testMapper->fetchByLevel($next_level->getId());

                if (count($tests) > 0) {
                    $this->view->next_test_id = $tests[0]->getId();
                } else {
                    //$result_url = '/user-tests/result-test/?test_id='.$test_id;
                    //return $this->_helper->redirector->gotoUrl('/user-tests/result-test/?test_id='.$test_id);
                }
            } else {
            //redirect to finish page
                //return $this->_helper->redirector->gotoUrl('/user-tests/result-test/?test_id='.$test_id);
            }
            //$this->view->next_test_id = 11;
            $this->view->ok_percent = ($all_ok * 100)/($all_ok + $all_fail);
            $this->view->all_ok = $all_ok;
            $this->view->all_fail = $all_fail;
            $this->view->results = $results;
            $this->view->session = $this->session;
            $this->view->questionnaires = $questionnaires;
            $this->view->test = $test;
        } catch (Exception $e) {
            $this->_helper->redirector("index");
        }


    }

    public function sendResultsAction() {

        try {
            $request = $this->getRequest();
            $from = $request->getParam('user');
            $content = $request->getParam('content');
            
            $mail = new Zend_Mail();
            $mail->setBodyHtml($content);
            $mail->setFrom($from, $from);
            $mail->addTo(EMAIL_RESULTS_TO, 'SHM');
            $mail->addTo($from);
            $mail->setSubject(EMAIL_RESULTS_SUBJECT);
            $mail->send();
        } catch (Exception $e){
            $this->_helper->json('fail');
        }

        $this->_helper->json('ok');
    }

    public function viewFailsAction() {

        $test_id = $this->_getParam("test_id");

        if ($test_id == null) {
            $this->_helper->redirector("index");
        }

        $questionnaire_id = $this->_getParam("questionnaire_id");

        if ($questionnaire_id == null) {
            $this->_helper->redirector("index");
        }

        $testMapper = new Application_Model_TestMapper();


        $data = array("id" => $test_id);
        $test = new Application_Model_Test($data);
        $testMapper->find($test_id, $test);


        $questionnaire = new Application_Model_Questionnaire();
        $questionnaireMapper = new Application_Model_QuestionnaireMapper();
        $questionnaireMapper->find($questionnaire_id, $questionnaire);

        $fails = array();

        foreach ($this->session->fail_responses[$questionnaire_id] as $index => $response) {

            $question_id = explode("_", $response[0]);
            $question_id = $question_id[1];
            $aux_q = new Application_Model_Question();
            $questionMapper = new Application_Model_QuestionMapper();
            $questionMapper->find($question_id, $aux_q);

            $question = str_replace("*", "", $aux_q->getQuestion());
            $fails[$question] = array("response" => $response[1], "ok_response" => $aux_q->getResult());
        }

        $this->_helper->layout()->setLayout('ajax');
        $this->view->fails = $fails;
        $this->view->questionnaire_name = $questionnaire->getName();

    }

    public function finalResultsAction() {

    }

    /*    public function addTestAction() {
      if ($this->_authNamespace->userRole == 'admin') {
      $request = $this->getRequest();
      $form = new Application_Form_Test();

      if ($this->getRequest()->isPost()) {
      if ($form->isValid($request->getPost())) {
      $test = new Application_Model_Test($form->getValues());
      $test->setName($form->getValue('name'));
      $test->setLevelId($form->getValue('level_id'));
      $mapper = new Application_Model_TestMapper();
      $mapper->save($test);
      return $this->_helper->redirector('index');
      }
      }

      $this->view->form = $form;
      } else {
      return $this->_helper->redirector('index');
      }
      }

      public function editTestAction() {

      if ($this->_authNamespace->userRole == 'admin') {
      $test_id = $this->_getParam("test_id");
      $request = $this->getRequest();
      $form = new Application_Form_Test();
      $this->view->test_id = $test_id;

      if ($this->getRequest()->isPost()) {
      if ($form->isValid($request->getPost())) {
      $data = array("id" => (int) $test_id);

      $test = new Application_Model_Test($data);
      $mapper = new Application_Model_TestMapper();
      $mapper->find($test_id, $test);
      $test->setName($form->getValue('name'));
      $test->setLevelId($form->getValue('level_id'));
      $mapper->save($test);

      return $this->_helper->redirector('index');
      }
      } else {
      $data = array("id" => (int) $test_id);

      $test = new Application_Model_Test($data);

      $mapper = new Application_Model_TestMapper();
      $mapper->find($test_id, $test);
      $form_data = array("id" => $test->getId(), "name" => $test->getName(), "level_id" => $test->getLevelId());
      $form->populate($form_data);

      $questionnaire = new Application_Model_QuestionnaireMapper();

      $this->view->allquestionnaires = $questionnaire->fetchAll();
      $this->view->questionnaires = $questionnaire->fetchByTest((int) $test_id);

      $this->view->level_id = $test->getLevelId();


      }


      $this->view->form = $form;
      } else {
      return $this->_helper->redirector('index');
      }
      }

      public function addQuestionnaireAction() {

      if ($this->_authNamespace->userRole == 'admin') {
      if ($this->getRequest()->isPost()) {
      $request = $this->getRequest();
      if ($request->getParam('q_id') != '-1') {
      try {

      $t_id = $request->getParam('t_id');
      $q_id = $request->getParam('q_id');


      $tq = new Application_Model_TestQuestionnaire();
      $tq->setTestId($t_id);
      $tq->setQuestionnaireId($q_id);
      $mapper = new Application_Model_TestQuestionnaireMapper();

      $result = $mapper->fetchByQuestionnaireTest($q_id, $t_id);

      if ($result == null) {
      $mapper->save($tq);
      $myResponse = array('ok');
      } else {
      $myResponse = array('repeated');
      }
      } catch (Exception $e) {
      $myResponse = array('fail');
      }
      } else {
      $myResponse = array('no-selected');
      }

      $this->_helper->json($myResponse);
      }
      }
      }

      public function removeQuestionnaireAction() {

      if ($this->_authNamespace->userRole == 'admin') {

      $request = $this->getRequest();
      try {

      $t_id = $request->getParam('t_id');
      $q_id = $request->getParam('q_id');
      $tq = new Application_Model_TestQuestionnaire();
      $tq->setTestId($t_id);
      $tq->setQuestionnaireId($q_id);
      $mapper = new Application_Model_TestQuestionnaireMapper();
      $result = $mapper->fetchByQuestionnaireTest($q_id, $t_id);

      if ($result == null) {
      $myResponse = 'fail';
      } else {
      $tq->setId($result->id);
      $mapper->delete($tq);
      $myResponse = array('ok');
      }
      } catch (Exception $e) {
      $myResponse = array('fail');
      }

      $this->_helper->json($myResponse);
      }
      }

      public function deleteAction() {
      if ($this->_authNamespace->userRole == 'admin') {
      $test_id = $this->_getParam("test_id");
      $this->view->idValue = $test_id;
      if ($test_id != null) {
      $data = array("id" => (int) $test_id);

      $test = new Application_Model_Test($data);
      $mapper = new Application_Model_TestMapper();
      $mapper->delete($test);

      $go = $this->_getParam("go");

      if ($go == '' or $go == null) {
      return $this->_helper->redirector('index');
      } else {
      return $this->_helper->redirector->gotoUrl($go);
      }
      }
      } else {
      $this->view->message = "You don't have permissions to do this!";
      return $this->_helper->redirector('index');
      }
      }
     */
}

